"""
@author: Leo
@version: 1.0.0
@file: wechat_utils.py
@time: 2023/9/5 8:13 PM
"""
import json
import logging
import os

import requests
from wechat_sdk import WechatBasic, WechatExt

from lab.common.enums import ErrorCodeEnum
from lab.common.response import BadRequest

logger = logging.getLogger(__name__)


class WechatUtilsWrapper:

    @staticmethod
    def get_union_id_via_mini_prog(code):
        app_id = os.getenv('MINI_PROG_APP_ID')
        secret_key = os.getenv('MINI_PROG_SECRET_KEY')
        url = f'https://api.weixin.qq.com/sns/jscode2session?appid={app_id}&secret={secret_key}&js_code={code}&grant_type=authorization_code'
        res = requests.get(url).json()
        logger.debug(f"app_id={app_id}, secret_key={secret_key}, open_id={code}, response={res}")
        if res.get('errcode'):
            raise BadRequest(ErrorCodeEnum.NETWORK_ERROR.value)
        return res.get('unionid')

    @staticmethod
    def get_open_id_via_mini_prog(code):
        app_id = os.getenv('MINI_PROG_APP_ID')
        secret_key = os.getenv('MINI_PROG_SECRET_KEY')
        url = f'https://api.weixin.qq.com/sns/jscode2session?appid={app_id}&secret={secret_key}&js_code={code}&grant_type=authorization_code'
        res = requests.get(url).json()
        logger.debug(f"app_id={app_id}, secret_key={secret_key}, open_id={code}, response={res}")
        if res.get('errcode'):
            raise BadRequest(ErrorCodeEnum.NETWORK_ERROR.value)
        return res.get('openid')

    @staticmethod
    def get_phone_number(code):
        app_id = os.getenv('MINI_PROG_APP_ID')
        secret_key = os.getenv('MINI_PROG_SECRET_KEY')
        access_token = WechatBasic(appid=app_id, appsecret=secret_key).get_access_token().get('access_token')
        url = f'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={access_token}'
        res = requests.post(url, data=json.dumps({'code': code})).json()
        logger.debug(f"app_id={app_id}, secret_key={secret_key}, open_id={code}, response={res}")
        if res.get('errcode'):
            raise BadRequest(ErrorCodeEnum.NETWORK_ERROR.value)
        return res.get('phone_info').get('phoneNumber')

    @staticmethod
    def get_union_id_via_qr_scan(open_id):
        app_id = os.getenv('H5_APP_ID')
        secret_key = os.getenv('H5_SECRET_KEY')
        url = f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={app_id}&secret={secret_key}&code={open_id}&grant_type=authorization_code'
        res = requests.get(url).json()
        logger.debug(f"app_id={app_id}, secret_key={secret_key}, open_id={open_id}, response={res}")
        if res.get('errcode'):
            raise BadRequest(ErrorCodeEnum.NETWORK_ERROR.value)
        return res.get('unionid')

    @staticmethod
    def get_union_id_via_official_account(open_id):
        app_id = os.getenv('OFFICIAL_ACCOUNT_APP_ID')
        secret_key = os.getenv('OFFICIAL_ACCOUNT_SECRET_KEY')
        url = f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={app_id}&secret={secret_key}&code={open_id}&grant_type=authorization_code'
        res = requests.get(url).json()
        logger.debug(f"app_id={app_id}, secret_key={secret_key}, open_id={open_id}, response={res}")
        if res.get('errcode'):
            raise BadRequest(ErrorCodeEnum.NETWORK_ERROR.value)
        return res.get('unionid')
